package com.hermit.qmst.UI.main;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.CallLog;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.hermit.qmst.MainActivity;
import com.hermit.qmst.MyApplication;
import com.hermit.qmst.R;
import com.hermit.qmst.UI.activity.CallingActivity;
import com.hermit.qmst.UI.activity.DialSetActivity;
import com.hermit.qmst.UI.activity.MessageAcitivity;
import com.hermit.qmst.UI.activity.SelectCallActivity;
import com.hermit.qmst.adapter.AdsViewPagerAdapter;
import com.hermit.qmst.adapter.CallLogAdapter;
import com.hermit.qmst.customView.MarqueeTextView;
import com.hermit.qmst.mode.CallLogInfo;
import com.hermit.qmst.request.RequestTask;
import com.hermit.qmst.request.RequestTaskInterface;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.FileUtils;
import com.hermit.qmst.tools.ImageDownLoader;
import com.hermit.qmst.tools.Log;
import com.hermit.qmst.tools.Preferences;
import com.hermit.qmst.tools.SipCallHelp;
import com.hermit.qmst.tools.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class DialFragment extends Fragment implements View.OnClickListener,
        RequestTaskInterface, LoaderManager.LoaderCallbacks<Cursor> {

    private static final String TAG = "CallLogFragment";

    private RelativeLayout mDialCallBar;
    private EditText metCallNum;
    private LinearLayout mDial;//键盘
    private static DialFragment mInstance;
    private View mView;
    private ImageButton mivAddContact;
    private TextView tv_message;
    private ViewPager mDialAdsViewPager;
    private AdsViewPagerAdapter mAdsViewPagerAdapter;
    private TextView mtvAdsMarquee;//滚动文字广告
    private FileUtils mFileUtils;
    // private RequestQueue mRequestQueue = null;
    private AudioManager mAudioManager;
    private static final int DTMF_DURATION_MS = 120;
    private Object mToneGeneratorLock = new Object();
    private ToneGenerator mToneGenerator;
    private static boolean mDTMFToneEnabled;
    private static final HashMap<String, Integer> mToneMap = new HashMap<String, Integer>();
    private Preferences mPreferences;
    private Vibrator mVibrator = null;//震动
    private ImageView mKey_del;
    private HashMap<String, String> mNumberToAlpha = new HashMap<String, String>();
    private LinearLayout ll_lunbo;
    private ListView mCallLogListView;

    //输入电话号码
    private CallLogAdapter mCallLogAdapter;
    //自动轮播的时间间隔
    private final static int TIME_INTERVAL = 5;
    //自动轮播启用开关
    private final static boolean isAutoPlay = true;
    //定时任务
    private ScheduledExecutorService scheduledExecutorService;
    //广告滚动位置
    private int mPosition = 0;
    //广告图片对应的链接
    private ArrayList<String> mImageToUrls = new ArrayList<>();
    //广告图片的链接
    private ArrayList<String> mImageUrls = new ArrayList<>();
    private LoaderManager mLoaderManager;
    private ArrayList<CallLogInfo> mCallLogList = new ArrayList<CallLogInfo>();
    private ArrayList<CallLogInfo> NewmCallLogList = new ArrayList<CallLogInfo>();
    private TextView tv_call_num;
    private TextView appTitle;
    private String agent;
    private FrameLayout fl_title_right;

    static {
        mToneMap.put("1", ToneGenerator.TONE_DTMF_1);
        mToneMap.put("2", ToneGenerator.TONE_DTMF_2);
        mToneMap.put("3", ToneGenerator.TONE_DTMF_3);
        mToneMap.put("4", ToneGenerator.TONE_DTMF_4);
        mToneMap.put("5", ToneGenerator.TONE_DTMF_5);
        mToneMap.put("6", ToneGenerator.TONE_DTMF_6);
        mToneMap.put("7", ToneGenerator.TONE_DTMF_7);
        mToneMap.put("8", ToneGenerator.TONE_DTMF_8);
        mToneMap.put("9", ToneGenerator.TONE_DTMF_9);
        mToneMap.put("0", ToneGenerator.TONE_DTMF_0);
        mToneMap.put("*", ToneGenerator.TONE_DTMF_S);
        mToneMap.put("#", ToneGenerator.TONE_DTMF_P);
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mDialAdsViewPager.setCurrentItem(mDialAdsViewPager.getCurrentItem() + 1);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //底部
        mDialCallBar = (RelativeLayout) LayoutInflater.from(getActivity()).inflate
                (R.layout.include_dial_call, null);
        mDialCallBar.setTag(MyApplication.DIAL_CALL_BAR_TAG);
        mInstance = this;
        mFileUtils = new FileUtils();
        initTone();

        mNumberToAlpha.put("2", "ABC");
        mNumberToAlpha.put("3", "DEF");
        mNumberToAlpha.put("4", "GHI");
        mNumberToAlpha.put("5", "JKL");
        mNumberToAlpha.put("6", "MNO");
        mNumberToAlpha.put("7", "PQRS");
        mNumberToAlpha.put("8", "TUV");
        mNumberToAlpha.put("9", "WXYZ");


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (mView == null) {
            mView = inflater.inflate(R.layout.activity_tab_dial, null);
            mLoaderManager = getLoaderManager();
            mLoaderManager.initLoader(1000, null, this);
        } else {
            ViewGroup vp = (ViewGroup) mView.getRootView();
            vp.removeView(mView);

        }

        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (metCallNum == null) {
            initView();
        } else {

            //fragment切换时，动画会恢复 即键盘恢复到原来的位置 在这里处理切回来时防止第一次点击拨号键 键盘动画向上

            if (metCallNum.getText().toString().length() > 0) {

                showDialCallBar(true);
            }

            mDial.setTag("up");
            mDial.setVisibility(View.VISIBLE);
            //显示广告
            showAds(true);
        }


    }

    @Override
    public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {

        /**
         * CursorLoader该类用于加载程序,查询ContentResolver并返回一个指针。这个类实现了装载机
         协议查询游标的标准方法,
         * 基于AsyncTaskLoader执行游标查询在一个后台线程,以便它不会阻止应用程序的UI。
         */
        Log.i("onCreateLoader", "id = " + id, true);
        CursorLoader loader = new CursorLoader(getActivity());
        //设置查询路径
        loader.setUri(CallLog.Calls.CONTENT_URI);
        //设置查询的列
        loader.setProjection(new String[]{CallLog.Calls._ID, CallLog.Calls.DATE,
                CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME, CallLog.Calls.TYPE});
        //设置查询条件 按时间顺序查询
        loader.setSortOrder(CallLog.Calls.DEFAULT_SORT_ORDER);
        return loader;
    }

    @Override
    public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data) {
        Log.i("onLoadFinished", "id = " + loader.getId(), true);

        boolean c = false;

        while (data.moveToNext()) {

            if (!c) {
                mCallLogList.clear();
                c = true;
            }

            CallLogInfo info = new CallLogInfo();
            String phone1 = "";//处理之后的
            String phone2 = "";//处理之前的
            phone2 = data.getString(data.getColumnIndex(CallLog.Calls.NUMBER));
            if (phone2 == null || phone2.length() == 0) {
                continue;
            }
            phone1 = Utils.analysePhoneNumber(phone2);
            if (phone1.length() < 7) {
                continue;
            }
            String name = data.getString(data.getColumnIndex(CallLog.Calls.CACHED_NAME));
            info.setName(name);

            info.setPhone1(phone1);
            info.setPhone2(phone2);
            info.setCallLogType(data.getInt(data.getColumnIndex(CallLog.Calls.TYPE)));
            info.setCalltime(data.getString(data.getColumnIndex(CallLog.Calls.DATE)));
//            info.setPhoneAera(data.getString(data.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL)));
            boolean isExist = false;
            //计算通话次数
            for (int i = 0; i < mCallLogList.size(); i++) {
                String preName = mCallLogList.get(i).getName();
                String prePhone2 = mCallLogList.get(i).getPhone2();


                if (prePhone2.equals(phone2)) {
                    int count = mCallLogList.get(i).getCallCount() + 1;
                    mCallLogList.get(i).setCallCount(count);
                    isExist = true;
                    break;
                }
            }

            if (!isExist) {
                mCallLogList.add(info);
            }
        }


    }

    @Override
    public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader) {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        if (mPreferences == null) {
            mPreferences = new Preferences(getActivity());
        }

        if (mAudioManager == null) {
            mAudioManager = (AudioManager) getActivity().getSystemService
                    (Context.AUDIO_SERVICE);
        }

        if (mVibrator == null) {
            getAdsFromLocal(null);
            mVibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
        }
        agent = Common.mAgentId;
        request_advert();
        request_ads_word();
        getMessage();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopPlay();
    }

    public static DialFragment getInstance() {
        return mInstance;
    }

    private void initView() {
        tv_call_num = (TextView) getActivity().findViewById(R.id.tv_call_num);
        metCallNum = (EditText) getActivity().findViewById(R.id.et_call_num);
        appTitle = (TextView) getActivity().findViewById(R.id.app_title);
        metCallNum.setFocusable(false);
        mtvAdsMarquee = (TextView) getActivity().findViewById(R.id.tv_ads_marquee);
        fl_title_right = (FrameLayout) getActivity().findViewById(R.id.fl_title_right);
        //拨号键盘按键初始化
        getActivity().findViewById(R.id.iv_dial_0).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_1).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_2).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_3).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_4).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_5).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_6).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_7).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_8).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_9).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_set).setOnClickListener(this);
        getActivity().findViewById(R.id.iv_dial_del).setOnClickListener(this);
        mKey_del = (ImageView) getActivity().findViewById(R.id.iv_dial_del);


        //拨号横条按键初始化
        mDialCallBar.findViewById(R.id.bt_dial).setOnClickListener(this);
        mDialCallBar.findViewById(R.id.bt_dial_contact).setVisibility(View.INVISIBLE);
        mDialCallBar.findViewById(R.id.bt_dial_gone).setVisibility(View.INVISIBLE);

        MainActivity.getInstance().mTabbar.addView(mDialCallBar, 0);

        mDial = (LinearLayout) getActivity().findViewById(R.id.dialpad);
        mivAddContact = (ImageButton) getActivity().findViewById(R.id.iv_title_right);
        tv_message = (TextView) getActivity().findViewById(R.id.tv_message);


        GradientDrawable drawable = (GradientDrawable) tv_message.getBackground();
        drawable.setColor(Color.parseColor("red"));
        mivAddContact.setOnClickListener(this);

        ll_lunbo = (LinearLayout) getActivity().findViewById(R.id.ads_dia_ll);
        mDialAdsViewPager = (ViewPager) getActivity().findViewById(R.id.ads_dial_vp);
        cu_tv_ads_marquee = (MarqueeTextView) getActivity().findViewById(R.id.cu_tv_ads_marquee);

        mCallLogListView = (ListView) mView.findViewById(R.id.lv_meetrecord);


        showDialCallBar(false);
        mCallLogAdapter = new CallLogAdapter(getActivity(), NewmCallLogList);
        mCallLogListView.setAdapter(mCallLogAdapter);
        initListener();


    }

    private MarqueeTextView cu_tv_ads_marquee;

    private void initListener() {


        mDialAdsViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int
                    positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {


            }
        });


        //长按删除键快速删除
        mKey_del.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                metCallNum.setText("");
                showAds(true);
                showDialCallBar(false);
                showMarquee(true);

                return false;
            }
        });
    }

    //初始化按键音设置
    private void initTone() {
        try {
            mDTMFToneEnabled = Settings.System.getInt(getActivity().getContentResolver(),
                    Settings.System.DTMF_TONE_WHEN_DIALING, 1) == 1;
            synchronized (mToneGeneratorLock) {
                if (mDTMFToneEnabled && mToneGenerator == null) {
                    mToneGenerator = new ToneGenerator(
                            AudioManager.STREAM_DTMF, 30);
                    getActivity().setVolumeControlStream(AudioManager.STREAM_DTMF);
                }
            }
        } catch (Exception e) {
            mDTMFToneEnabled = false;
            mToneGenerator = null;
        }

    }

    private void playTone(int tone) {


        if (mPreferences.getPreferenceBooleanValue(Preferences.DIAL_KEY_VIBRATE)) {
            mVibrator.vibrate(DTMF_DURATION_MS);
            // mVibrator.vibrate(new long[]{100,10,100,1000},-1);
        }

        if (!mPreferences.getPreferenceBooleanValue(Preferences.DIAL_KEY_TONE)) {
            return;
        }

        int ringMode = mAudioManager.getRingerMode();
        if (ringMode == AudioManager.RINGER_MODE_SILENT
                || ringMode == AudioManager.RINGER_MODE_VIBRATE) {
            return;
        }

        synchronized (mToneGeneratorLock) {
            if (mToneGenerator == null) {
                return;
            }
            mToneGenerator.startTone(tone, DTMF_DURATION_MS);
        }

    }

    /**
     * 开始轮播图切换
     */

    private void startPlay() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
        }
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4,
                TimeUnit.SECONDS);
    }

    /**
     * 停止轮播图切换
     */
    private void stopPlay() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
        }
    }

    /**
     * 执行轮播图切换任务
     */
    private class SlideShowTask implements Runnable {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            synchronized (mDialAdsViewPager) {
                mHandler.obtainMessage().sendToTarget();
            }
        }

    }

    //从本地获取广告
    private void getAdsFromLocal(JSONArray dataArr) {

        JSONArray array = null;
        if (dataArr == null) {//从本地获取保存的数据
            try {
                String str = mFileUtils.readTxt(Common.getDialImageDirPath(),
                        Common.mTxtFileName);
                if (str == null) {
                    return;
                }

                array = new JSONArray(str);

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            array = dataArr;
        }
        //读取图片
        try {
            ArrayList<String> urlList = new ArrayList<>();
            mImageToUrls.clear();
//            mImageToUrls.add(array.getJSONObject(array.length()-1).getString("url"));
            for (int i = 0; i < array.length(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                if (!jsonObject.getString("img").equals("")) {
                    String imgUrl = jsonObject.getString("img");
                    String url = jsonObject.getString("url");
                    urlList.add(imgUrl);
                    mImageToUrls.add(url);
                }
            }
//            mImageToUrls.add(array.length(),array.getJSONObject(0).getString("url"));


            if (urlList.size() > 0) {

                mImageUrls = urlList;

                if (mAdsViewPagerAdapter == null) {
                    mAdsViewPagerAdapter = new AdsViewPagerAdapter(urlList, mImageToUrls,
                            getActivity());
                    mDialAdsViewPager.setAdapter(mAdsViewPagerAdapter);
                    showAds(true);
                } else {
                    mAdsViewPagerAdapter.setImageUrlList(urlList);
                }
            } else {

                mAdsViewPagerAdapter = null;
                mDialAdsViewPager.setVisibility(View.GONE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (array != null) {
            try {
                mFileUtils.saveTxtFile(Common.getDialImageDirPath(), Common.mTxtFileName,
                        array.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    //显示广告
    private void showAds(boolean show) {

        if (mAdsViewPagerAdapter != null && show && metCallNum.getText().toString().length()
                == 0) {
            mDialAdsViewPager.setVisibility(View.VISIBLE);
            startPlay();
        } else {
            mDialAdsViewPager.setVisibility(View.VISIBLE);
            stopPlay();
        }


    }

    //广告游字

    private void request_ads_word() {
        String url = Common.submitQueryTextPath();
        Log.i(TAG, "submitQueryText = " + url, true);
        String param = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><type>advertising_word</type><uid>" + agent + "</uid><phone>" + Common.myPhone
                + "</phone></data>";
        RequestTask task = new RequestTask(this, url, param, "POST", getActivity());
        task.execute();
    }

    //请求广告信息
    private void request_advert() {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.getCache().clear();


        String url = Common.submitQueryPicPath();
        Log.i(TAG, "submitQueryPicPath = " + url, true);

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.i(TAG, "onResponse:" + jsonObject.toString(), true);
//                        Toast.makeText(getActivity(),jsonObject.toString(),Toast.LENGTH_LONG).show();
                        try {
                            if (jsonObject != null && jsonObject.getInt("status") == 1) {

                                JSONArray dataArr = jsonObject.getJSONArray("data");

                                getAdsFromLocal(dataArr);
                                Log.i(TAG, "广告信息 = " + dataArr.toString(), true);


                            } else {
                                if (mAdsViewPagerAdapter != null) {

                                    mFileUtils.deleteFile(Common.getDialImageDirPath() + "/" +
                                            Common.mTxtFileName);
                                    mImageToUrls.clear();
                                    mImageUrls.clear();
                                    Log.i(TAG, "mImageUrls" + mImageUrls.toString(), true);
                                    mAdsViewPagerAdapter = new AdsViewPagerAdapter(mImageUrls,
                                            mImageToUrls, getActivity());
                                    mDialAdsViewPager.setAdapter(mAdsViewPagerAdapter);
                                    mDialAdsViewPager.setVisibility(View.GONE);
                                    mAdsViewPagerAdapter = null;
                                } else {
                                    mDialAdsViewPager.setVisibility(View.INVISIBLE);
                                }

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            ll_lunbo.setVisibility(View.INVISIBLE);
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }
        ) {
            @Override
            public byte[] getBody() {

                String requestParam = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><data><type>dial_pic</type><uid>" + agent + "</uid><phone>" + Common.myPhone +
                        "</phone></data>";
                Log.i(TAG, "submitQueryPicPath = " + requestParam, true);
                byte[] b = null;
                try {
                    b = requestParam.getBytes("utf-8");
                } catch (Exception e) {
                    b = requestParam.getBytes();
                }
                return b;
            }
        };
        requestQueue.add(request);


    }

    /**
     * 获取顶部图标和数量
     */
    private void getMessage() {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        String url = Common.submitMessageCount() + "&aid=" + agent + "&uid=" + Common.mUserId;
        Log.i(TAG, "getMessage url= " + url, true);
        JsonObjectRequest request = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject object) {
                try {
                    Log.i(TAG, "getMessage = " + object.toString(), true);
                    if (object.getString("state").equals("1")) {
                        if (object.getInt("count") > 0) {
                            tv_message.setText(object.getInt("count") + "");
                            String url = object.getString("img");
                            if (url.length() > 0) {
                                ImageDownLoader imageDownLoader = new ImageDownLoader(getActivity());
                                Bitmap bitmap = imageDownLoader.downloadImage(Common.getDialImageDirPath(), url, new ImageDownLoader.onImageLoaderListener() {
                                    @Override
                                    public void onImageLoader(Bitmap bitmap, String url) {
                                        Drawable drawable = new BitmapDrawable(getActivity().getApplicationContext().getResources(), bitmap);
                                        mivAddContact.setBackgroundDrawable(drawable);
                                    }
                                });
                                if (bitmap != null) {
                                    mivAddContact.setBackgroundDrawable(new BitmapDrawable(getActivity().getApplicationContext().getResources(), bitmap));
                                } else {
                                    mivAddContact.setBackgroundResource(R.drawable.nav_bar_messages);
                                }
                            } else {
                                fl_title_right.setVisibility(View.GONE);
                            }
                        } else {
                            fl_title_right.setVisibility(View.GONE);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    fl_title_right.setVisibility(View.GONE);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                fl_title_right.setVisibility(View.VISIBLE);
            }
        });
        requestQueue.add(request);
    }

    //mDialCallBar动画显示隐藏
    private void showDialCallBar(boolean isShow) {
        //显示
        if (isShow) {
            Animation a = AnimationUtils.loadAnimation(getActivity(),
                    R.anim.translucent_upin);
            // a.setFillAfter(true);
            mDialCallBar.startAnimation(a);
            mDialCallBar.setVisibility(View.VISIBLE);

            ll_lunbo.setVisibility(View.GONE);
            mCallLogListView.setVisibility(View.VISIBLE);
            tv_call_num.setVisibility(View.VISIBLE);
//            }
            //隐藏
        } else {
            Animation a = AnimationUtils.loadAnimation(getActivity(),
                    R.anim.translucent_downout);
            // a.setFillAfter(true);
            mDialCallBar.startAnimation(a);
            mDialCallBar.setVisibility(View.GONE);


            ll_lunbo.setVisibility(View.VISIBLE);
            mCallLogListView.setVisibility(View.GONE);
            tv_call_num.setVisibility(View.GONE);
            if (NewmCallLogList.size() > 0) {
                NewmCallLogList.clear();
            }
        }
    }


    //电话号码输入框
    private void inputPhoneNum(String num) {

        String phone = metCallNum.getText().toString();
        if (phone.length() > 12) {
            return;
        }

        showMarquee(false);
        //有数字输入隐藏广告
        //showAds(false);

        phone += num;
        metCallNum.setText(phone);
        tv_call_num.setText(phone);
        SearchPhone(phone);
        mCallLogAdapter.notifyDataSetChanged();
        if (phone.length() == 1) {
            showDialCallBar(true);
        }


    }

    private void SearchPhone(String phone) {
        if (NewmCallLogList.size() > 0) {
            NewmCallLogList.clear();
        }
        int count = mCallLogList.size();
        for (int i = 0; i < count; i++) {
            if (mCallLogList.get(i).getPhone1().contains(phone)) {
                NewmCallLogList.add(mCallLogList.get(i));
            }
        }
    }

    //删除输入框号码
    private void deletePhoneNum() {
        String phone = metCallNum.getText().toString();
        if (phone.length() > 0) {
            phone = phone.substring(0, phone.length() - 1);
            metCallNum.setText(phone);
            tv_call_num.setText(phone);
            SearchPhone(phone);
            if (metCallNum.getText().length() == 0) {

                showMarquee(true);
                showDialCallBar(false);
            }

            if (phone.length() == 0) {
                //显示广告
                //showAds(true);
            } else {

            }
        }
    }

    //显示或隐藏滚动字幕
    private void showMarquee(boolean b) {
        if (b) {
            mtvAdsMarquee.setSelected(true);
//            mtvAdsMarquee.setVisibility(View.VISIBLE);
        } else {
            mtvAdsMarquee.setSelected(false);
//            mtvAdsMarquee.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.iv_dial_0:
                inputPhoneNum("0");
                playTone(mToneMap.get("0"));
                break;
            case R.id.iv_dial_1:
                inputPhoneNum("1");
                playTone(mToneMap.get("1"));
                break;
            case R.id.iv_dial_2:
                inputPhoneNum("2");
                playTone(mToneMap.get("2"));
                break;
            case R.id.iv_dial_3:
                inputPhoneNum("3");
                playTone(mToneMap.get("3"));
                break;
            case R.id.iv_dial_4:
                inputPhoneNum("4");
                playTone(mToneMap.get("4"));
                break;
            case R.id.iv_dial_5:
                inputPhoneNum("5");
                playTone(mToneMap.get("5"));
                break;
            case R.id.iv_dial_6:
                inputPhoneNum("6");
                playTone(mToneMap.get("6"));
                break;
            case R.id.iv_dial_7:
                inputPhoneNum("7");
                playTone(mToneMap.get("7"));
                break;
            case R.id.iv_dial_8:
                inputPhoneNum("8");
                playTone(mToneMap.get("8"));
                break;
            case R.id.iv_dial_9:
                inputPhoneNum("9");
                playTone(mToneMap.get("9"));
                break;
            case R.id.iv_dial_del:
                deletePhoneNum();
                playTone(mToneMap.get("*"));
                break;
            case R.id.iv_dial_set:
                //设置
                Intent dialSetintent = new Intent(getActivity(), DialSetActivity.class);
                startActivity(dialSetintent);
                getActivity().overridePendingTransition(R.anim.fling_in_right2left,
                        R.anim.fling_out_left2right);
                playTone(mToneMap.get("#"));
                break;

            case R.id.bt_dial_gone:
                showDialCallBar(false);
                break;
            case R.id.bt_dial_contact:
                MainActivity.getInstance().setCurrentFragment(4);
                break;
            case R.id.bt_dial:

                String callphone = metCallNum.getText().toString();
                Common.mCallPhone = callphone;
                Common.mCallAera = null;
                Common.mCallName = null;
                //清空输入框号码
                metCallNum.setText("");
                //关闭底部拨号条
                showDialCallBar(false);
                showMarquee(true);

                String type = mPreferences.getPreferenceStringValue(Preferences.CALL_WAY);
                if (type.equals("0")) {//回拨

                    Intent callIntent = new Intent(getActivity(), CallingActivity.class);
                    startActivity(callIntent);
                    getActivity().overridePendingTransition(R.anim.fling_in_right2left,
                            R.anim.fling_out_left2right);
                } else if (type.equals("1")) {//直拨
                    SipCallHelp.placeCallWithOption(null, getActivity(), callphone);
                } else if (type.equals("2")) {//智能拨打

                    if (Common.checkWIFI(getActivity())) {
                        SipCallHelp.placeCallWithOption(null, getActivity(), callphone);
                    } else {
                        Intent callIntent = new Intent(getActivity(), CallingActivity.class);
                        startActivity(callIntent);
                        getActivity().overridePendingTransition(R.anim.fling_in_right2left,
                                R.anim.fling_out_left2right);
                    }

                } else {

                    Intent callIntent = new Intent(getActivity(), SelectCallActivity.class);
                    startActivity(callIntent);
                    getActivity().overridePendingTransition(R.anim.fling_in_right2left,
                            R.anim.fling_out_left2right);

                }
                break;
            case R.id.iv_title_right:
                Intent shareIntent = new Intent(getActivity(), MessageAcitivity.class);
                startActivityForResult(shareIntent, 2);
//                startActivity(shareIntent);
                break;
        }

    }

    @Override
    public void postExecute(String paramString) {
        Log.i(TAG, "paramString = " + paramString, true);
        if (paramString == null || paramString.length() == 0) {
            return;
        }

        try {

            JSONObject jsonObject = new JSONObject(paramString);
            if (jsonObject.getString("status").equals("1")) {
                JSONArray dataArr = jsonObject.getJSONArray("data");
                if (dataArr.length() > 0) {
                    JSONObject item = dataArr.getJSONObject(0);
                    String str = item.getString("content");
                    Log.i(TAG, "content = " + str, true);
                    cu_tv_ads_marquee.setText(str);
                    appTitle.setText(item.getString("title"));
//                    mtvAdsMarquee.setText(str);
                }
            } else {
                mDialAdsViewPager.setVisibility(View.INVISIBLE);
                cu_tv_ads_marquee.setText("");
                appTitle.setText("");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            getMessage();
        }
    }
}
